package top.archiesean.authorize.support.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import top.archiesean.common.core.domain.R;
import top.archiesean.common.core.enums.RespStatus;
import top.archiesean.common.core.utils.resp.ResponseUtils;

import java.io.IOException;

/**
 * @author ArchieSean
 * @description 认证失败异常处理
 * @date 2024-01-05 07:13
 */
@Slf4j
public class AuthenticationFailureEventHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String username = request.getParameter(OAuth2ParameterNames.USERNAME);
        log.info("用户：{} 登录失败，异常：{}", username, exception.getLocalizedMessage());
        //todo,此处根据需要是否进行日志埋点操作


        //写出错误信息
        ResponseUtils.out(response, R.fail(RespStatus.UNAUTHORIZED));
    }
}
